<template>
  <div class="course-card">
    <div class="card-inner">
      <!-- Course Image Section -->
      <div class="card-image">
        <img :src="course.coverImage || defaultImage" :alt="course.title" class="cover-image" />
        
        <div class="image-overlay">
          <div class="quick-actions">
            <el-button 
              circle 
              :type="isFavorited ? 'danger' : ''" 
              size="small" 
              @click.stop="toggleFavorite"
              :loading="favoriteLoading"
            >
              <el-icon v-if="isFavorited"><StarFilled /></el-icon>
              <el-icon v-else><Star /></el-icon>
            </el-button>
          </div>
        </div>
        
        <div class="card-badges">
          <span class="difficulty-badge" :class="difficultyClass">
            {{ course.difficulty }}
          </span>
        </div>
      </div>
      
      <!-- Course Content Section -->
      <div class="card-content">
        <div class="card-meta">
          <span class="institution">{{ course.institution }}</span>
          <span class="duration"><el-icon><Clock /></el-icon> {{ formatDuration(course.duration) }}</span>
        </div>
        
        <h3 class="card-title" :title="course.title">{{ course.title }}</h3>
        
        <p v-if="course.subtitle" class="card-subtitle">{{ course.subtitle }}</p>
        
        <div class="card-tags">
          <el-tag size="small" type="info" effect="plain">{{ course.subject }}</el-tag>
          <el-tag size="small" type="info" effect="plain" v-if="course.language">{{ course.language }}</el-tag>
        </div>
        
        <div class="card-stats">
          <span class="stat-item" v-if="course.viewCount !== undefined">
            <el-icon><View /></el-icon> {{ course.viewCount }}
          </span>
          <span class="stat-item" v-if="course.heatScore !== undefined">
            <el-icon><Histogram /></el-icon> {{ course.heatScore }}
          </span>
        </div>
        
        <div class="card-action">
          <el-button type="primary" @click.stop="viewCourse">查看详情</el-button>
          <el-button 
            :type="isFavorited ? 'danger' : ''" 
            @click.stop="toggleFavorite"
            :loading="favoriteLoading"
          >
            <el-icon><component :is="isFavorited ? 'StarFilled' : 'Star'" /></el-icon>
            {{ isFavorited ? '取消收藏' : '收藏' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { 
  School, 
  Clock, 
  Document, 
  Star, 
  StarFilled, 
  View,
  Histogram
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  course: {
    type: Object,
    required: true
  },
  alreadyFavorited: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['favorite-changed'])

const router = useRouter()
const userStore = useUserStore()
const isFavorited = ref(props.alreadyFavorited)
const favoriteLoading = ref(false)
const defaultImage = '/images/course-placeholder.jpg'

// 监听 alreadyFavorited 属性变化
watch(() => props.alreadyFavorited, (newVal) => {
  isFavorited.value = newVal;
});

onMounted(async () => {
  if (userStore.isLoggedIn && !props.alreadyFavorited) {
    await checkFavoriteStatus()
  } else {
    isFavorited.value = props.alreadyFavorited
  }
})

// 根据难度设置不同的样式类
const difficultyClass = computed(() => {
  if (!props.course.difficulty) return ''
  
  switch (props.course.difficulty) {
    case '初级':
      return 'beginner'
    case '中级':
      return 'intermediate'
    case '高级':
      return 'advanced'
    default:
      return ''
  }
})

// 跳转到课程详情页
const viewCourse = () => {
  router.push(`/courses/${props.course.id}`)
}

// 格式化课程时长
const formatDuration = (minutes) => {
  if (!minutes) return '未知时长'
  
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  
  if (hours > 0) {
    return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`
  }
  
  return `${mins}分钟`
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  if (!userStore.isLoggedIn) return
  
  try {
    const params = {
      userId: userStore.userInfo.id,
      courseId: props.course.id
    }
    
    await request.get('/favorite/check', params, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        isFavorited.value = data
      },
      onError: (error) => {
        console.error('检查收藏状态失败:', error)
      }
    })
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 切换收藏状态
const toggleFavorite = async (event) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation()
  
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再收藏课程')
    router.push('/login')
    return
  }
  
  favoriteLoading.value = true
  
  try {
    if (isFavorited.value) {
      // 取消收藏
      await request.delete('/favorite?userId=' + userStore.userInfo.id + '&courseId=' + props.course.id, {
        successMsg: '已取消收藏',
        onSuccess: () => {
          isFavorited.value = false
          emit('favorite-changed', { courseId: props.course.id, favorited: false })
        },
        onError: (error) => {
          console.error('取消收藏失败:', error)
        }
      })
    } else {
      // 添加收藏
      const data = {
        userId: userStore.userInfo.id,
        courseId: props.course.id
      }
      
      await request.post('/favorite', data, {
        successMsg: '收藏成功',
        onSuccess: () => {
          isFavorited.value = true
          emit('favorite-changed', { courseId: props.course.id, favorited: true })
        },
        onError: (error) => {
          console.error('添加收藏失败:', error)
        }
      })
    }
  } catch (error) {
    console.error('操作收藏失败:', error)
  } finally {
    favoriteLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.course-card {
  height: 100%;
  transition: all 0.3s ease;
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  background: var(--el-bg-color);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  
  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
    
    .cover-image {
      transform: scale(1.05);
    }
    
    .image-overlay {
      opacity: 1;
    }
  }

  .card-inner {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  
  .card-image {
    position: relative;
    height: 180px;
    overflow: hidden;
    
    .cover-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.5s ease;
    }
    
    .image-overlay {
      position: absolute;
      inset: 0;
      background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.5));
      display: flex;
      align-items: flex-start;
      justify-content: flex-end;
      padding: 12px;
      opacity: 0;
      transition: opacity 0.3s ease;
    }
    
    .quick-actions {
      z-index: 2;
    }
    
    .card-badges {
      position: absolute;
      bottom: 12px;
      left: 12px;
      display: flex;
      gap: 8px;
      z-index: 2;
    }
    
    .difficulty-badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 50px;
      font-size: 12px;
      font-weight: 600;
      color: white;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      
      &.beginner {
        background: linear-gradient(135deg, #67c23a, #85ce61);
      }
      
      &.intermediate {
        background: linear-gradient(135deg, #e6a23c, #f3d19e);
      }
      
      &.advanced {
        background: linear-gradient(135deg, #f56c6c, #f89898);
      }
    }
  }
  
  .card-content {
    padding: 16px;
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .card-meta {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    color: var(--el-text-color-secondary);
    margin-bottom: 8px;
    
    .institution {
      font-weight: 500;
      max-width: 60%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .duration {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }
  
  .card-title {
    margin: 0 0 8px 0;
    font-size: 18px;
    font-weight: 600;
    line-height: 1.4;
    color: var(--el-text-color-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    min-height: 50px;
  }
  
  .card-subtitle {
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin: 0 0 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    min-height: 42px;
  }
  
  .card-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 12px;
  }
  
  .card-stats {
    display: flex;
    gap: 12px;
    font-size: 13px;
    color: var(--el-text-color-secondary);
    margin-bottom: 16px;
    
    .stat-item {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }
  
  .card-action {
    margin-top: auto;
    display: flex;
    gap: 10px;
    
    .el-button {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }
}

// Dark mode enhancements
@media (prefers-color-scheme: dark) {
  .course-card {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    
    &:hover {
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.3);
    }
  }
}

// Touch device optimization
@media (hover: none) {
  .course-card {
    .image-overlay {
      opacity: 1;
      background: linear-gradient(to bottom, rgba(0,0,0,0.05), rgba(0,0,0,0.3));
    }
  }
}
</style> 